package com.briup.impl.server;

import com.briup.entity.Environment;
import com.briup.inter.Configuration;
import com.briup.inter.server.DBStore;
import com.briup.inter.server.Server;
import com.briup.inter.support.ConfigurationAware;
import com.briup.inter.support.PropertiesAware;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.*;


public class ServerImplTest implements Server, ConfigurationAware, PropertiesAware {
    private Logger log = Logger.getLogger(ServerImpl.class);

    private DBStore dbStore;
    private int port;
    ExecutorService pool = Executors.newFixedThreadPool(5);
    @Override
    public void receive() throws Exception {

        try (ServerSocket ss = new ServerSocket(port)) {
            log.info("启动服务端 " + port + " 等待链接");
            while (!Thread.currentThread().isInterrupted()) { // 检查是否中断了线程
                Socket clientSocket = ss.accept(); // 接受客户端连接
                pool.submit(() -> {
                    try (InputStream is = clientSocket.getInputStream();
                         ObjectInputStream ois = new ObjectInputStream(is)) {
                        // 2.接收数据
                        List<Environment> list = null;
                        list = (List<Environment>) ois.readObject();
                        log.debug("服务端接收到数据 " + list.size());
                        dbStore.saveDB(list);
                    } catch (Exception e) {
                        log.error("处理客户端数据时发生错误", e);
                    } finally {
                        try {
                            clientSocket.close(); // 关闭客户端连接
                        } catch (IOException e) {
                            log.error("关闭客户端连接时发生错误", e);
                        }
                    }
                });
            }
        } catch (Exception e) {
            log.error("服务器启动或运行时发生错误", e);
        } finally {
            pool.shutdown();
        }
    }

    @Override
    public void shutdown() throws Exception { // 关闭接收服务器

    }

    @Override
    public void setConfiguration(Configuration configuration) throws Exception {
        dbStore = configuration.getDbStore();
    }

    @Override
    public void init(Properties properties) throws Exception {
        port = Integer.parseInt((String) properties.get("server-port"));
    }



}
